package com.fengye.feign;

import cn.hutool.json.JSONUtil;
import com.fengye.feign.api.UploadMata;
import com.fengye.feign.clients.FeignProviderClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.fengye.feign.clients")
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @RestController
    class TestController {

        private static final Logger logger = LoggerFactory.getLogger(TestController.class);

        @Autowired
        private FeignProviderClient provider;

        // 测试接口
        @GetMapping("/consumer/test/{name}")
        public String test(@PathVariable(value = "name") String name) {
            return "hello " + name;
        }

        @PostMapping("/consumer/test/upload/{name}")
        public String testFeignUpload(@PathVariable(value = "name") String name) {
            byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
            MultipartFile file = new MockMultipartFile("file", "feign.txt", "text/plain", bytes);
            UploadMata uploadMata = new UploadMata();
            uploadMata.setContentType("text/plain");
            uploadMata.setFileName("feign.txt");
            uploadMata.setFileSize(bytes.length);
            return provider.upload(file, JSONUtil.toJsonStr(uploadMata));
        }

        @GetMapping("/consumer/test/provider/{name}")
        public String testProvider(@PathVariable(value = "name") String name) {
            logger.info("testProvider name:{}", name);
            return provider.test(name);
        }
    }
}
